<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">


      <!-- 使用 flex 布局，将 el-dropdown 和 el-button 自动排列到合适的位置 -->

      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width: 10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item v-for="(item, index) in tableTitle" :key="index" :command="item.label" v-if="item.tableProp !== 'status'">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <el-button @click="handleSearch" :disabled="search ? false:true">搜索</el-button>

      <p style="color: rgb(80,80,80);">状态</p>
      <el-dropdown @command="handleStatus">
        <el-button type="primary" style="width: 10vw;">
          {{Status}}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item command="未审核">未审核</el-dropdown-item>
          <el-dropdown-item command="已拒绝">已拒绝</el-dropdown-item>
          <el-dropdown-item command="已通过">已通过</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>

    </el-header>

    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item, index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label" :formatter="formatFlag" :width="item.width"></el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: space-around; gap: 0px;">
              <el-button @click="handleAccept(scope.row)" type="text" size="small" style="flex-grow: 1;" v-if="scope.row.status===0 && scope.row.code===0">同意</el-button>
              <el-button @click="handleRefuse(scope.row)" type="text" size="small" style="flex-grow: 1;" v-if="scope.row.status===0 && scope.row.code===0">拒绝</el-button>
              <el-button @click="handleDelete(scope.row)" type="text" size="small" style="flex-grow: 1;">删除</el-button>
            </div>
          </template>
        </el-table-column>


      </el-table>
    </el-main>
    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>

<script>
import http from '@/utils/http';
import { checkToken } from '@/router/index';

export default {
  data() {
    return {
      searchFilter:[],
      Status:'全部',
      filteredList:[],
      Filter:'全部',
      search :"",
      currentPage: 1,
      pageSize: 10,
      allInfo:[],
      tableTitle:[
        {tableProp:"id",label:"审核ID"},
        {tableProp:"carNumber",label:"车牌号"},
        {tableProp:"landlordName",label:"提交人"},

        {tableProp:"createTime",label:"审核提交时间", width: "180"},
        {tableProp:"dealTime",label:"审核处理时间", width: "180"},
        {tableProp:"adminName",label:"处理人"},
        {tableProp:"status",label:"审核状态"},

      ],
      tableData: [],
      loading:false,
    }
  },
  computed: {

    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted(){
    this.getAllData();
  },
  methods: {
    handleRefresh(){
      this.getAllData();
      this.handleReset();
    },
    handleAccept(row){
      //更新前端


      //更新数据库
      this.verifyToDatabase(row.id,1);
    },
    handleRefuse(row){
      //更新前端

      //更新数据库
      this.verifyToDatabase(row.id,0);
    },
    verifyToDatabase(id,status){ //向数据库提交审核状态，0为已拒绝，1为通过
      http.get("/admin/car/verifyCar",{
        params:{
          id:id,
          decide:status,
        }
      }).then(response=>{
        console.log(response.data.data);
        this.handleRefresh();
      }).catch((error) => {
        console.log("request error !");
        console.error(error);
      });
    },
    formatFlag(row, column, cellValue) {
      const statusMap = {
        0: '未审核',
        1: '已通过',
        2: '已拒绝'
      };

      if (column.property === 'status') {
        return statusMap[cellValue] || '未知状态';
      }

      if (column.property === 'dealTime' || column.property === 'adminName') {
        return cellValue || '暂无';
      }
      return cellValue;
    },
    getAllData(){
      this.loading=true;
      http.get("/admin/car/getCarVerify")
          .then((response) => {
            console.log("request succeed!");
            const Result = response.data;
            this.allInfo = Result.data;
            // 根据申请时间降序排序
            this.allInfo.sort((a, b) => {
              return new Date(b.createTime) - new Date(a.createTime);
            });
            //this.addOtherInfo();
            this.tableData = this.allInfo;
            this.loading=false;
          }).catch((error) => {
        console.log("request error !");
        console.error(error);
      });
    },
    /*    addOtherInfo(){
          this.allInfo.forEach(item => {
            http.get().then().catch((error) => {
              console.log("request error !");
              console.error(error);
            });
          });
        },*/
    addnew() {
      this.tableData.push({});
    },
    handleReset(){
      this.search = "";
      this.Filter = "全部";
      this.Status = "全部";
      this.tableData = this.allInfo;
    },
    handleStatus(command){
      this.Status = command;

      this.handleSearch();  // 在更新状态后调用 handleSearch

    },
    handleFilter(command) {
      this.Filter = command;
      this.handleSearch();  // 在更新过滤器后调用 handleSearch
    },
    handleSearch() {
      let filteredData = this.allInfo;

      // 首先进行搜索过滤
      if (this.search) {
        filteredData = filteredData.filter(item => {
          if (this.Filter === "全部") {
            return Object.keys(item).some(key => {
              if (key === 'status') {
                return false;
              }
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });
          } else {
            const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
            const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
            return value.includes(this.search.toLowerCase());
          }
        });
      }

      // 然后进行状态过滤
      if (this.Status !== '全部') {
        let st = -1;
        switch(this.Status){
          case '未审核':
            st = 0;
            break;
          case '已拒绝':
            st = 2;
            break;
          case '已通过':
            st = 1;
            break;
        }
        filteredData = filteredData.filter(item => item.status === st);
      }

      this.tableData = filteredData;
    },
    handleDetails(row) {
      console.log('详情', row);
    },
    //删除按钮
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({

          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    deleteData(row){
      // 删除界面上的
      this.tableData = this.tableData.filter(item=>item!==row);
      // 更新总数据源
      this.allInfo = this.tableData;

      // 检查当前页是否大于删除后的数据页数，若是则重置为前一页
      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }
      // //删除数据库中
      http.get("/admin/car/deleteVerify",{
        params:{
          id: row.id
        }
      }).then(response=>{
        console.log(response.data.data);
      })
    }
    ,
    handlePageChange(page) {
      this.currentPage = page;
    }
  }
}
</script>

<style scoped lang="scss">
/* Add custom styling for your component */
</style>
